<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="实体类型" prop="entityType" >
        <el-select v-model="queryParams.entityType" @keyup.enter.native="handleQuery" clearable style="width: 260px">
          <el-option value="1" label="仓库">仓库</el-option>
          <el-option value="2" label="客户">客户</el-option>
          <el-option value="3" label="供应商">供应商</el-option>
          <el-option value="4" label="会员">会员</el-option>
          <el-option value="5" label="门店">门店</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地址类型" prop="addressType">
        <el-select v-model="queryParams.addressType" @keyup.enter.native="handleQuery" clearable  style="width: 260px">
          <el-option value="1" label="发货地址">发货地址</el-option>
          <el-option value="2" label="收货地址">收货地址</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input  style="width: 260px"
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="telephone">
        <el-input  style="width: 260px"
          v-model="queryParams.telephone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input  style="width: 260px"
          v-model="queryParams.address"
          placeholder="请输入详细地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="默认地址" prop="isDefault" >
        <el-select v-model="queryParams.isDefault" @keyup.enter.native="handleQuery" clearable  style="width: 260px">
          <el-option value="1" label="是">是</el-option>
          <el-option value="0" label="否">否</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:Address:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:Address:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:Address:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:Address:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="AddressList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="序号" align="center" prop="id" />-->
      <el-table-column label="实体类型" align="center" prop="entityType" >
        <template slot-scope="scope">
          <span>{{ scope.row.entityType == 1 ? "仓库" : scope.row.entityType == 2 ? "客户" : scope.row.entityType == 3 ? "供应商" : scope.row.entityType == 4 ? "会员" : "门店"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="实体名称" align="center" prop="entityId" />
      <el-table-column label="地址类型" align="center" prop="addressType" >
        <template slot-scope="scope">
          <span>{{ scope.row.addressType == 2 ? "收货地址" : "发货地址"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="手机号" align="center" prop="telephone"width="140" />

      <el-table-column label="地区" align="center"  show-overflow-tooltip prop="cityId"/>

<!--      <el-table-column label="详细地址" align="center" prop="address" />-->
      <el-table-column label="是否默认地址" align="center" prop="isDefault" >
        <template slot-scope="scope">
          <span>{{ scope.row.isDefault == 1 ? "是" : "否"}}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="createBy" width="120"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="getShow(scope.row)"
            v-hasPermi="['system:Address:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:Address:edit']"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:Address:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改地址库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="实体类型" prop="entityType" >
          <el-select v-model="form.entityType" @keyup.enter.native="handleQuery" clearable @change="handleSelectChange" style="width: 380px">
            <el-option :value="1" label="仓库">仓库</el-option>
            <el-option :value="2" label="客户">客户</el-option>
            <el-option :value="3" label="供应商">供应商</el-option>
            <el-option :value="4" label="会员">会员</el-option>
            <el-option :value="5" label="门店">门店</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实体" prop="entityId" v-if="form.entityType != null" >
          <el-select v-model="form.entityId" @keyup.enter.native="handleQuery" clearable style="width: 380px">
            <el-option v-for="x in xiala"
                       :key="x.id"
                       :value="x.name"
                       :label="x.name">{{x.name}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址类型" prop="addressType" >
          <el-select v-model="form.addressType" @keyup.enter.native="handleQuery" clearable style="width: 380px">
            <el-option :value="1" label="发货地址">发货地址</el-option>
            <el-option :value="2" label="收货地址">收货地址</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="地区" prop="cityId">
          <el-cascader style="width: 380px"
             v-model="form.cityId"
             :options="options1"
             :props="{
              value:'id',
              label:'name',
              children:'children',expandTrigger: 'hover'
            }"
             clearable
             @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="是否默认地址" prop="isDefault">
          <el-switch v-model="form.isDefault" active-text="是" inactive-text="否" :active-value='1'
                     :inactive-value='0'></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看" :visible.sync="open1" width="700px" append-to-body>
      <el-descriptions :column="2" border :data="haseShow">
        <el-descriptions-item label="实体类型">{{haseShow.entityType == 1 ? "仓库" : haseShow.entityType == 2 ? "客户" : haseShow.entityType == 3 ? "供应商" : haseShow.entityType == 4 ? "会员" : haseShow.entityType == 5 ? "门店" : "" }}</el-descriptions-item>
        <el-descriptions-item label="实体">{{haseShow.entityId}}</el-descriptions-item>
        <el-descriptions-item label="地址类型">{{haseShow.addressType == 1 ? "发货地址" : haseShow.addressType == 2 ? "收货地址" : ""}}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{haseShow.name}}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{haseShow.telephone}}</el-descriptions-item>
        <el-descriptions-item label="地区">{{haseShow.cityId}}</el-descriptions-item>
        <el-descriptions-item label="详细地址" :span="2">{{haseShow.address}}</el-descriptions-item>
        <el-descriptions-item label="默认地址" :span="2">{{haseShow.isDefault == 1 ? "是" : "否"}}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { listAddress, getAddress, delAddress, addAddress, updateAddress } from "@/api/system/Address";
import { listCity,listCity1 } from '@/api/system/City'
import { listStoreCenterInfo } from '@/api/system/StoreCenterInfo'
import { listCustomer } from '@/api/system/Customer'
import { listSupplier } from '@/api/system/Supplier'
import { listMember } from '@/api/system/Member'
import { listShop } from '@/api/system/Shop'


export default {
  name: "Address",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 地址库表格数据
      AddressList: [],
      AddressList1:[],
      value: [],
      options1:[],
      options2:[],
      xiala:[],
      haseShow:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        entityType: null,
        addressType: null,
        name: null,
        telephone: null,
        address: null,
        isDefault: null,
      },
      queryParams1: {
        pageNum: 1,
        pageSize: 100000
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        entityId: [
          { required: true, message: "实体不能为空", trigger: "blur" }
        ],
        entityType: [
          { required: true, message: "实体类型不能为空", trigger: "change" }
        ],
        addressType: [
          { required: true, message: "地址类型不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        telephone: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        cityId: [
          { required: true, message: "地区不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        isDefault: [
          { required: true, message: "是否默认地址不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    //级联下拉框
    this.getCityList();
    this.getCityList1();

  },
  methods: {
    handleSelectChange(){
      this.form.entityId=null;
      if(this.form.entityType == 1){
        this.getList1();
      }else if(this.form.entityType == 2){
        this.getList2();
      }else if(this.form.entityType == 3){
        this.getList3();
      }else if (this.form.entityType == 4){
        this.getList4();
      }else if (this.form.entityType == 5){
        this.getList5();
      }
      this.loading = false; // 确保关闭加载
    },
    getCityList() {
      this.loading = true;
      listCity(this.queryParams1).then(response => {
        this.options1 = response.rows;
        this.loading = false;
      });
    },
    getCityList1() {
      this.loading = true;
      listCity1(this.queryParams1).then(response => {
        this.options2 = response.rows;
        var add = this.AddressList;
        var cityId = [];
        for (let i = 0; i < add.length; i++) {
          //分割
          cityId.push(add[i].cityId.split("/"));
        }
        for (let j = 0;j<cityId.length;j++){
          for(let i=0; i<cityId[j].length; i++){
            for (let k = 0;k<this.options2.length;k++){
              if (cityId[j][i] == this.options2[k].id){
                cityId[j][i] = this.options2[k].name;
              }
            }
          }
        }
        for (let i=0; i<cityId.length; i++){
          cityId[i]=cityId[i].join('/');
        }
        for (let i=0; i<this.AddressList.length; i++){
          this.AddressList[i].cityId  = cityId[i];
        }
        console.log(this.AddressList);
        this.loading = false;
      });
    },

    /** 查询地址库列表 */
    getList() {
      this.loading = true;
      listAddress(this.queryParams).then(response => {
        this.AddressList = response.rows;
        // this.SelectCity();
        // this.AddressList1 = this.AddressList;
        this.total = response.total;
        this.loading = false;
      });
    },
    getList1() {
      this.loading = true;
      listStoreCenterInfo(this.queryParams1).then(response => {
        this.xiala = response.rows;
      });
    },
    getList2() {
      this.loading = true;
      listCustomer(this.queryParams1).then(response => {
        this.xiala = response.rows;
      });
    },
    getList3() {
      this.loading = true;
      listSupplier(this.queryParams1).then(response => {
        this.xiala = response.rows;
      });
    },
    getList4() {
      this.loading = true;
      listMember(this.queryParams1).then(response => {
        this.xiala = response.rows;
      });
    },
    getList5() {
      this.loading = true;
      listShop(this.queryParams1).then(response => {
        this.xiala = response.rows;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        entityId: null,
        entityType: null,
        addressType: null,
        name: null,
        telephone: null,
        cityId: null,
        address: null,
        isDefault: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      //级联下拉框
      this.value=[];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getCityList1();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加地址库";
    },

    //查看按钮操作
    getShow(row) {
      this.loading = true;
      const id = row.id || this.ids
      getAddress(id).then(response => {
        this.haseShow = response.data;
        if (this.haseShow.cityId != null || this.haseShow.cityId != ""){
          var fenge = this.haseShow.cityId.split("/");
          for (let j = 0;j<fenge.length;j++) {
            for (let k = 0; k < this.options2.length; k++) {
              if (fenge[j] == this.options2[k].id) {
                fenge[j] = this.options2[k].name;
              }
            }
          }
        }
        fenge=fenge.join('/');
        this.haseShow.cityId  = fenge;
        this.open1=true;
        this.loading = false;
        this.title = "查看";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAddress(id).then(response => {
        this.form = response.data;
        //级联下拉框
        if(this.form.cityId != null){
          const codes = this.form.cityId.split("/");
          this.form.cityId = codes;
        }
        if(this.form.entityType == 1){
          this.getList1();
        }else if(this.form.entityType == 2){
          this.getList2();
        }else if(this.form.entityType == 3){
          this.getList3();
        }else if (this.form.entityType == 4){
          this.getList4();
        }else if (this.form.entityType == 5){
          this.getList5();
        }
        this.loading = false; // 确保关闭加载
        this.open = true;
        this.title = "修改地址库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            //级联下拉框
            const str = this.form.cityId;
            var str1="";
            for(var i=0; i<str.length; i++){
              if(i == str.length-1){
                str1 += str[i];
                break;
              }
              str1 += str[i]+"/";
            }
            this.form.cityId = str1;
            updateAddress(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getCityList1();
            });
          } else {
            //级联下拉框
            const str = this.form.cityId;
            var str1="";
            for(var i=0; i<str.length; i++){
              if(i == str.length-1){
                str1 += str[i];
                break;
              }
              str1 += str[i]+"/";
            }
            this.form.cityId = str1;
            addAddress(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getCityList1();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除地址库编号为"' + ids + '"的数据项？').then(function() {
        return delAddress(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/Address/export', {
        ...this.queryParams
      }, `Address_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
